package com.spring.boot.demo.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.spring.boot.demo.bean.City;
import com.spring.boot.demo.mapper.CityMapper;
import com.spring.boot.demo.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CityServiceImpl implements CityService {

    @Autowired
    private CityMapper cityMapper;

    @Transactional
    @Override
    public void insertCity() {
        City city = new City();
        city.setName("长沙1");
        city.setAge(200);

        cityMapper.insertCity(city);

        SpringUtil.getBean(CityService.class).insertCity2();

        // 此时测试，insertCity2 执行未回滚，但是事务1回滚了
//        throw new RuntimeException("xxx");
    }

    /**
     * 模拟单线程有2个不同的事务
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void insertCity2() {
        City city = new City();
        city.setName("长沙2");
        city.setAge(200);

        cityMapper.insertCity(city);
    }

}
